package edu.fudan.jwxt.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import edu.fudan.jwxt.annotation.Adminer;
import edu.fudan.jwxt.common.Constants;
import edu.fudan.jwxt.common.ResultBody;
import edu.fudan.jwxt.entity.Major;
import edu.fudan.jwxt.service.MajorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/majors")
public class MajorController {
    @Autowired
    private MajorService majorService;

    @GetMapping
    public ResultBody majorListAll(){
        List<Major> majors = majorService.list();

        return ResultBody.success(majors);
    }

    @GetMapping("/{majorId}")
    public ResultBody getMajor(@PathVariable int majorId){

        Major major = majorService.getById(majorId);

        return ResultBody.success(major);
    }


    @GetMapping("/college/{collegeId}")
    public ResultBody getLinkMajors(@PathVariable int collegeId){
        LambdaQueryWrapper<Major> q = new LambdaQueryWrapper<>();
        q.eq(Major::getCollegeId,collegeId);
        List<Major> majors = majorService.list(q);

        return ResultBody.success(majors);
    }

    //TODO: 用户权限检查
    @PostMapping("/update")
    public ResultBody updateMajor(@RequestBody Major major){
        majorService.updateById(major);
        return ResultBody.success();
    }

    //TODO: 用户权限检查
    @PostMapping("/insert")
    public ResultBody insertMajor(@RequestBody Major major){
        majorService.save(major);

        return ResultBody.success();
    }

    //TODO: 用户权限检查
    @PostMapping("/inserts")
    public ResultBody insertMajorList(@RequestBody List<Major> majors){
        for(Major major : majors)
            majorService.save(major);

        return ResultBody.success();
    }

    //TODO: 用户权限检查
    @DeleteMapping("/{majorId}")
    public ResultBody delete(@PathVariable int majorId){

        boolean falg = majorService.removeById(majorId);
        if(falg)
            return ResultBody.success();
        else
            return ResultBody.error(Constants.CODE_600,"不存在该专业");

    }

    //TODO: 用户权限检查
    @PostMapping("/delete")
    public ResultBody deleteList(@RequestBody List<Integer> ids){

        int faliCount = 0;
        for (int id : ids) {
            try {
                majorService.removeById(id);
            }catch(Exception e){
                faliCount++;
            }
        }
        if(faliCount == 0)
            return ResultBody.success();
        else
            return ResultBody.error(Constants.CODE_600,"部分专业无法删除");
    }



}
